package com.offcn.seckill.listener;

import com.alibaba.fastjson.JSON;
import com.offcn.seckill.service.SeckillOrderService;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class SeckillMsgListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    @RabbitListener(bindings =
        @QueueBinding(
                value = @Queue,
                exchange = @Exchange(value = "com.offcn.seckill.exchange"),
                key = "com.offcn.seckill.routingkey"
        )
    )
    public void seckillMsg(String msg) {
        System.out.println(msg);
        Map map = JSON.parseObject(msg, Map.class);
        // 支付状态
        String trade_status = (String) map.get("trade_status");
        if(trade_status != null && trade_status.equals("TRADE_SUCCESS")) {
            // 用户名
            String username = (String) map.get("username");
            // 交易订单ID
            String out_trade_no = (String) map.get("out_trade_no");
            // 支付宝流水号
            String trade_no = (String) map.get("trade_no");
            // 调用修改订单的方法
            seckillOrderService.updatePayStatus(out_trade_no, trade_no, username);
        }

    }
}
